import { defineStore } from 'pinia';
import { computed, ref } from 'vue';

const useSearchStore = defineStore(
  'search',
  () => {
    const histories = ref<string[]>([]);

    const historiesGetter = computed(() => histories.value);

    const addHistory = (newHistoryItem: string) => {
      const index = histories.value.findIndex(item => item === newHistoryItem);
      if (index >= 0) {
        histories.value.splice(index, 1);
      }

      histories.value.unshift(newHistoryItem);
    };
    const deleteHistory = (index: number) => {
      histories.value.splice(index, 1);
    };
    const clearHistory = () => {
      histories.value = [];
    };

    return {
      histories,
      historiesGetter,
      addHistory,
      deleteHistory,
      clearHistory
    };
  },
  {
    persist: [
      {
        pick: ['histories'],
        storage: localStorage
      }
    ]
  }
);

export default useSearchStore;
